package service

import (
	"jtvss/api/operation/model"
	"jtvss/pkg/orm"
)

// 主组织
func OrganizationPrimary(guid string) (model.Organization, error) {
	var data model.Organization
	err := orm.DB().Model(&data).Where("guid = ? AND parent_id = 0", guid).First(&data).Error
	return data, err
}

type Orgainze struct {
	ID       int        `json:"id"`   //
	Name     string     `json:"name"` // 名称
	ParentID int        `json:"parentId"`
	Count    int        `json:"count" gorm:"-"`
	Vehicles []Vehicle  `json:"vehis,omitempty" gorm:"-"`
	Children []Orgainze `json:"children,omitempty" gorm:"-"`
}

func (o *Orgainze) filterChildren(data []Orgainze, vehis []Vehicle) {
	nid := o.ID
	if o.ParentID == 0 {
		nid = 0
	}
	for _, v := range vehis {
		if nid != v.OrganizeID {
			continue
		}
		o.Vehicles = append(o.Vehicles, v)
		o.Count++
	}
	for _, v := range data {
		if v.ParentID != o.ID {
			continue
		}
		v.filterChildren(data, vehis)
		o.Children = append(o.Children, v)
		o.Count += v.Count
	}
}

func OrganizeTree(guid string, vehis []Vehicle) (tree []Orgainze) {
	var data []Orgainze
	orm.DB().Model(&model.Organization{}).Find(&data, "guid = ?", guid)
	for _, v := range data {
		if v.ParentID != 0 {
			continue
		}
		v.filterChildren(data, vehis)
		tree = append(tree, v)
	}
	return
}
